<template>
  <div class="content-wrap">
    <!-- 检索区域 -->
    <el-form class="search-wrap" :inline="true" :model="searchFormData">
      <!-- 测试人员 -->
      <el-form-item class="search-wrap-item" label="测试人员：">
        <el-select
          class="search-select"
          placeholder="全部"
          v-model="searchFormData.sysUserId"
          clearable
          filterable
          @change="handleSearch"
        >
          <el-option
            v-for="item in testOptions"
            :key="item.id"
            :label="item.testName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <!-- 项目名称 -->
      <el-form-item class="search-wrap-item" label="项目名称：">
        <el-select
          class="search-select"
          placeholder="全部"
          v-model="searchFormData.itemItemId"
          clearable
          filterable
          @change="handleSearch"
        >
          <el-option
            v-for="item in projecOptions"
            :key="item.ID"
            :label="item.itemName"
            :value="item.ID"
          />
        </el-select>
      </el-form-item>
      <!-- wikiL类型-->
      <el-form-item class="search-wrap-item" label="wiki类型：">
        <el-select
          class="search-select"
          style="width: 220px;"
          placeholder="全部"
          v-model="searchFormData.itemWIKITypeId"
          clearable
          filterable
          @change="handleSearch"
        >
          <el-option
            v-for="item in wikiOptions"
            :key="item.ID"
            :label="item.typeName"
            :value="item.ID"
          />
        </el-select>
      </el-form-item>
      <!-- 需求名称 -->
      <el-form-item class="search-wrap-item" label="问题描述：">
        <el-input
          v-model="searchFormData.problemMsg"
          style="width: 240px"
          placeholder="请输入问题描述"
          clearable
          @input="handleSearch"
        ></el-input>
      </el-form-item>
      <!-- 创建时间 -->
      <el-form-item class="search-wrap-item" label="创建时间：">
        <el-date-picker
          style="width: 240px"
          v-model="searchFormData.timeFrame"
          type="daterange"
          unlink-panels
          range-separator="-"
          start-placeholder="开始时间"
          end-placeholder="结束时间"
          :shortcuts="shortcuts"
          @change="handleSearch"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
      </el-form-item>
      <el-form-item>
        <el-button
          style="font-size: 12px; padding: auto 15px"
          type="primary"
          @click="handleExport"
        >
          <el-icon :size="16"><Document /></el-icon>
          &nbsp;&nbsp;下载</el-button
        >
      </el-form-item>
    </el-form>
    <!-- 表格区域 -->
    <el-card class="card-wrap" v-loading="loading">
      <div class="card-wrap-fun">
        <!-- 功能区域 -->
        <el-button type="primary" @click="initDialogForm(null)">
          <el-icon>
            <Plus />
          </el-icon>
          <span>添加wiki</span>
        </el-button>
      </div>
      <!-- 数据展示区域 -->
      <div class="card-wrap-table">
        <el-table
          :data="demandsList"
          border
          :max-height="'100vh - 280px'"
          style="width: 100%"
          :header-cell-style="tableHeaderStyle"
          :row-style="tableRowStyle"
          @row-dblclick="handleViewRequire"
        >
          <el-table-column
            fixed
            type="index"
            label="序号"
            width="60"
            align="center"
          />
          <el-table-column label="登记人" width="100" align="center">
            <template #="{ row }">
              <span>{{ row.createUser }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="projectName"
            label="项目名称"
            width="140"
            align="center"
          />
          <el-table-column
            prop="problemMsg"
            label="问题描述"
            width="500"
            align="center"
          />
          <el-table-column
            prop="problemReason"
            label="问题原因"
            width="500"
            align="center"
          />
          <el-table-column
            prop="trueResult"
            label="处理结果"
            width="500"
            align="center"
          />
          <el-table-column
            prop="beginDate"
            label="开始时间"
            width="200"
            sortable
            :formatter="timeDate"
            align="center"
          />
          <el-table-column
            prop="endDate"
            label="结束时间"
            width="200"
            sortable
            :formatter="timeDate"
            align="center"
          />
          <el-table-column
            prop="processingDate"
            label="处理时间"
            width="160"
            align="center"
          />
          <el-table-column label="是否解决" width="100" align="center">
            <template #="{ row }">
              <span
                :style="{ color: row.isTrue == 1 ? 'green' : 'red' }"
                style="font-weight: bold"
                >{{ row.isTrue == 1 ? "是" : "否" }}</span
              >
            </template>
          </el-table-column>
          <el-table-column label="是否归档" width="100" align="center">
            <template #="{ row }">
              <span
                :style="{ color: row.isArchiving == 1 ? 'green' : 'red' }"
                style="font-weight: bold"
                >{{ row.isArchiving == 1 ? "是" : "否" }}</span
              >
            </template>
          </el-table-column>
          <el-table-column
            prop="auxiliaryUser"
            label="辅助处理人"
            width="140"
            align="center"
          />
          <el-table-column
            prop="developmentBBTime"
            label="研发响应时间"
            width="140"
            align="center"
          />
          <el-table-column
            prop="archivingUrl"
            label="归档地址"
            width="140"
            align="center"
          />
          <!-- <el-table-column label="处理留证" width="600" align="center">
            <template #="{ row }">
              <el-scrollbar>
                <div :style="requirementContetnStyle" v-dompurify-html="row.problemPhoto"></div>
              </el-scrollbar>
            </template>
          </el-table-column> -->
          <el-table-column
            label="操作"
            align="center"
            width="250"
            fixed="right"
            border
          >
            <template #="{ row }">
              <!-- 查看 -->
              <el-button
                class="table-operation table-operation-view"
                @click="handleViewRequire(row.ID)"
              >
                <el-icon>
                  <View />
                </el-icon>
              </el-button>
              <!-- 修改 -->
              <el-button
                id="addBtn"
                class="table-operation table-operation-edit"
                @click="initDialogForm(row)"
              >
                <el-icon>
                  <Edit />
                </el-icon>
              </el-button>
              <!-- 归档 -->
              <el-button
                class="table-operation table-operation-wallet"
                @click="isArchivingForm(row)"
              >
                <el-icon>
                  <Wallet />
                </el-icon>
              </el-button>
              <!-- 删除 -->
              <el-popconfirm
                title="确定要删除该wiki吗？"
                @confirm="handleDelRequire(row.ID)"
                @cancel="handleCancelDel"
                width="200px"
              >
                <template #reference>
                  <el-button class="table-operation table-operation-del">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 分页区域 -->
      <div class="page-wrap">
        <Pagination
          v-model:currten-page="pageInfo.page"
          :page-size="pageInfo.pageSize"
          :total="pageInfo.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></Pagination>
      </div>
    </el-card>

    <!-- 添加/修改需求弹窗 -->
    <el-dialog
      id="dialogForm"
      v-model="dialogTableVisible"
      :title="titleDialogText + 'wiki'"
      width="1000"
      :show-close="true"
      :before-close="handleBeforeCancel"
    >
      <el-form
        class="dialog-form"
        :inline="true"
        ref="dialogFormRef"
        :model="dialogFormData"
        :rules="ruleDialogForm"
        label-position="left"
        label-width="120px"
      >
        <el-form-item label="项目名称：" prop="itemItemId" required>
          <el-select
            style="width: 160px"
            placeholder="请选择项目"
            v-model="dialogFormData.itemItemId"
            clearable
          >
            <el-option
              v-for="item in projecOptions"
              :key="item.ID"
              :label="item.itemName"
              :value="item.ID"
            />
          </el-select>
        </el-form-item>

        <el-form-item
          label="wiki类型："
          prop="itemWIKITypeId"
          required
          style="margin-left: 230px"
        >
          <el-select
            style="width: 160px"
            placeholder="请选择类型"
            v-model="dialogFormData.itemWIKITypeId"
            clearable
          >
            <el-option
              v-for="wiki in wikiOptions"
              :key="wiki.ID"
              :label="wiki.typeName"
              :value="wiki.ID"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="问题描述：" prop="problemMsg" required>
          <el-input
            v-model="dialogFormData.problemMsg"
            placeholder="请输入问题描述"
            :input-style="{ width: '800px' }"
          ></el-input>
        </el-form-item>
        <el-form-item label="问题原因：" prop="problemReason" required>
          <el-input
            v-model="dialogFormData.problemReason"
            placeholder="请输入问题原因"
            :input-style="{ width: '800px' }"
          ></el-input>
        </el-form-item>
        <el-form-item label="处理情况：" prop="trueResult" required>
          <el-input
            v-model="dialogFormData.trueResult"
            placeholder="请输入处理情况"
            :input-style="{ width: '800px' }"
          ></el-input>
        </el-form-item>
        <el-form-item label=" 开始时间：" prop="beginDate" required>
          <el-date-picker
            v-model="dialogFormData.beginDate"
            type="datetime"
            placeholder="请选择日期"
          />
        </el-form-item>
        <el-form-item
          label=" 结束时间："
          prop="endDate"
          required
          style="margin-left: 170px"
        >
          <el-date-picker
            v-model="dialogFormData.endDate"
            type="datetime"
            placeholder="请选择日期"
          />
        </el-form-item>
        <el-form-item label="参与人：" prop="auxiliaryUser">
          <el-input
            v-model="dialogFormData.auxiliaryUser"
            placeholder="请输入参与人"
            :input-style="{ width: '800px' }"
          ></el-input>
        </el-form-item>
        <el-form-item label="研发响应时间：" prop="developmentBBTime">
          <el-input
            v-model="dialogFormData.developmentBBTime"
            placeholder="请输入研发响应时间"
            :input-style="{ width: '800px' }"
          ></el-input>
        </el-form-item>
        <el-form-item label="是否解决" prop="isTrue" required>
          <el-select
            style="width: 160px"
            placeholder="请选择"
            v-model="dialogFormData.isTrue"
            clearable
          >
            <el-option :key="1" label="是" :value="1" />
            <el-option :key="2" label="否" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理留证" prop="problemPhoto" required>
          <EditorVue
            class="editor"
            :modelValue="dialogFormData.problemPhoto"
            @update:modelValue="updateModelValue"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleCancel">取消</el-button>
          <el-button type="primary" @click="handleAddRequire"> 确定 </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 查看需求 -->
    <el-dialog
      class="dialog-view-container"
      title="WIKI详细信息"
      :show-close="true"
      width="1200px"
      v-model="dialogViewVisible"
    >
      <el-row :gutter="20">
        <el-col :span="3">
          <span class="dialog-view-requireTitle">项目名称:</span>
        </el-col>
        <el-col :span="5">{{ dialogViewData.projectName }}</el-col>
        <el-col :span="3">
          <span class="dialog-view-requireTitle">wiki类型:</span>
        </el-col>
        <el-col :span="5">{{ dialogViewData.itemWIKITypeName }}</el-col>
        <el-col :span="3">
          <span class="dialog-view-requireTitle">创建人:</span>
        </el-col>
        <el-col :span="5">{{ dialogViewData.createUser }}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="3">
          <span class="dialog-view-requireTitle">问题原因:</span>
        </el-col>
        <el-col :span="10">{{ dialogViewData.problemReason }}</el-col>
        <el-col :span="3">
          <span class="dialog-view-requireTitle">问题描述:</span>
        </el-col>
        <el-col :span="8">{{ dialogViewData.problemMsg }}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="3">
          <span class="dialog-view-requireTitle">处理结果:</span>
        </el-col>
        <el-col :span="21">{{ dialogViewData.trueResult }}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="3">
          <span class="dialog-view-requireTitle">辅助处理人:</span>
        </el-col>
        <el-col :span="21">{{ dialogViewData.auxiliaryUser }}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="3">
          <span class="dialog-view-requireTitle">开始时间:</span>
        </el-col>
        <el-col :span="9">{{ dialogViewData.beginDate }}</el-col>
        <el-col :span="3">
          <span class="dialog-view-requireTitle">结束时间:</span>
        </el-col>
        <el-col :span="9">{{ dialogViewData.endDate }}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="3">
          <span class="dialog-view-requireTitle">处理时间:</span>
        </el-col>
        <el-col :span="9">{{ dialogViewData.processingDate }}</el-col>
        <el-col :span="3">
          <span class="dialog-view-requireTitle">是否解决:</span>
        </el-col>
        <el-col
          :span="9"
          :style="{ color: dialogViewData.isTrue == 1 ? 'green' : 'red' }"
          >{{ dialogViewData.isTrue == 1 ? "是" : "否" }}</el-col
        >
      </el-row>
      <el-row :gutter="20">
        <el-col :span="3">
          <span class="dialog-view-requireTitle">是否归档:</span>
        </el-col>
        <el-col
          :span="9"
          :style="{ color: dialogViewData.isArchiving == 1 ? 'green' : 'red' }"
          >{{ dialogViewData.isArchiving == 1 ? "是" : "否" }}</el-col
        >
        <el-col :span="3">
          <span class="dialog-view-requireTitle">归档地址:</span>
        </el-col>
        <el-col :span="9">{{ dialogViewData.archivingUrl }}</el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="3">
          <span class="dialog-view-requireTitle">处理留证:</span>
        </el-col>
        <el-col :span="21">
          <el-scrollbar style="max-height: 500px">
            <div
              ref="content"
              :style="requirementContetnStyle"
              v-dompurify-html="dialogViewData.problemPhoto"
            ></div>
          </el-scrollbar>
        </el-col>

        <!-- 弹出层展示放大图片 -->
        <el-dialog v-model="dialogVisible" width="80%" height="80%">
          <img
            :src="currentImageSrc"
            class="el-image-viewer__img"
            style="
              transform: scale(1) rotate(0deg) translate(0px, 0px);
              max-height: 100%;
              max-width: 100%;
            "
          />
        </el-dialog>
      </el-row>
    </el-dialog>

    <!-- 上传、审核用例 -->
    <el-dialog
      v-model="dialogTestVisible"
      title="需求用例"
      width="80%"
      :show-close="true"
      :before-close="closeCasesDialog"
    >
      <!-- 上传用例 -->
      <el-upload
        ref="uploadCase"
        class="upload-demo"
        action="#"
        :limit="1"
        :before-upload="handleBeforeUpload"
      >
        <template #trigger>
          <el-button type="primary">上传用例</el-button>
        </template>
        <template #tip>
          <p>{{ uploadTipText }}</p>
        </template>
      </el-upload>
      <!-- 用例数据表格 -->
      <el-scrollbar max-height="600px">
        <el-table height="600px" :data="initCaseData" border>
          <el-table-column
            fixed
            type="index"
            label="序号"
            width="60"
            align="center"
          />
          <el-table-column
            label="用例名称"
            min-width="200"
            header-align="center"
            property="caseName"
            show-overflow-tooltip
            fixed="left"
            border
          >
            <template #="{ row }">
              <span class="cell-ellipsis">{{ row.caseName }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="用例编写人"
            width="100"
            align="center"
            property="caseEditMembers"
          ></el-table-column>
          <el-table-column
            label="更新时间"
            width="120"
            align="center"
            property="caseEditDate"
            sortable
            :formatter="timeDate"
          ></el-table-column>
          <el-table-column
            label="用例得分"
            width="100"
            align="center"
            property="caseScore"
          ></el-table-column>
          <el-table-column
            label="是否能复用"
            width="100"
            align="center"
            property="isCaseReuse"
          >
            <template #="{ row }">
              <span
                :style="{ color: row.isCaseReuse == '否' ? 'red' : 'green' }"
                >{{ row.isCaseReuse }}</span
              >
            </template>
          </el-table-column>
          <el-table-column
            label="是否是补充用例"
            width="100"
            align="center"
            property="isCaseAdd"
          >
            <template #="{ row }">
              <span
                :style="{ color: row.isCaseAdd == '否' ? 'red' : 'green' }"
                >{{ row.isCaseAdd }}</span
              >
            </template>
          </el-table-column>
          <el-table-column
            label="用例质量"
            width="100"
            align="center"
            property="caseQuality"
          >
            <template #="{ row }">
              <span :style="{ color: getQualityColor(row.caseQuality) }">{{
                row.caseQuality === 3
                  ? "优"
                  : row.caseQuality === 2
                  ? "良"
                  : "差"
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="审核状态"
            width="100"
            align="center"
            property="isAudit"
          >
            <template #="{ row }">
              <span :style="{ color: row.isAudit == 0 ? 'red' : 'green' }">{{
                row.isAudit === 0 ? "未审核" : "已审核"
              }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="180"
            fixed="right"
            border
          >
            <template #="{ row }">
              <!-- 审核 -->
              <el-button
                class="table-operation table-operation-view"
                @click="handleAuditTest(row)"
              >
                <el-icon>
                  <SetUp />
                </el-icon>
              </el-button>
              <!-- 修改 -->
              <el-button
                id="addBtn"
                class="table-operation table-operation-edit"
                @click="handleEditTest(row)"
              >
                <el-icon>
                  <Edit />
                </el-icon>
              </el-button>
              <!-- 删除 -->
              <el-popconfirm
                title="确定要删除该需求吗？"
                @confirm="handleDelTest(row.ID)"
                @cancel="handleCancelDel"
                width="200px"
              >
                <template #reference>
                  <el-button class="table-operation table-operation-del">
                    <el-icon>
                      <Delete />
                    </el-icon>
                  </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </el-scrollbar>
    </el-dialog>

    <!-- 修改用例弹窗 -->
    <el-dialog
      title="用例详情"
      v-model="caseVisible"
      :show-close="true"
      :before-close="closeCaseDialog"
    >
      <el-form ref="caseDlgFormRef" v-model="caseDlgFormData">
        <el-form-item label="用例名称:">
          <el-input
            type="text"
            v-model="caseDlgFormData.caseName"
            placeholder="请输入用例名称"
          />
        </el-form-item>
        <el-form-item label="操作步骤:">
          <el-input
            type="textarea"
            :rows="5"
            v-model="caseDlgFormData.operationSteps"
            placeholder="请输入操作步骤"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="预期结果:">
          <el-input
            type="textarea"
            :rows="5"
            v-model="caseDlgFormData.expectedResult"
            placeholder="请输入预期结果"
          />
        </el-form-item>
        <el-form-item label="实际结果:">
          <el-input
            type="textarea"
            :rows="5"
            v-model="caseDlgFormData.realResult"
            placeholder="请输入实际结果"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeCaseDialog">取消</el-button>
          <el-button type="primary" @click="submitCaseFormData">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 是否归档弹框 -->
    <el-dialog
      v-model="dialogWikiIsArchivingVisible"
      :show-close="true"
      :before-colse="closeWikiArchivingDialog"
      title="wiki归档"
    >
      <!-- 审核用例 -->
      <el-form ref="archivingFormRef" :model="archivingFormData">
        <el-form-item label="归档地址：">
          <el-input v-model="archivingFormData.archivingUrl" />
        </el-form-item>
        <el-form-item label="是否归档：">
          <el-switch
            v-model="archivingFormData.isArchiving"
            inline-prompt
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeWikiArchivingDialog">取消</el-button>
          <el-button type="primary" @click="submitWikiArchivingFormData">
            确认
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import EditorVue from "./editor.vue";
import request from "@/utils/request";
import { onMounted, ref, reactive, nextTick } from "vue";
import {
  getTestList,
  getItemList,
  getRequirementCase,
  postUploadCaseFile,
  postRequirementCase,
  delCaseByid,
  putWikiArchiving,
  putEditeCaseByid,
  getWikiTypeList,
  postAddWIki,
  getWikiList,
  getWikiMsg,
  editWikiMsg,
  delWiki,
  getWikiTypeById,
  // exportWikis,
} from "@/api/project/index";
import { ElMessage } from "element-plus";
import Pagination from "@/components/Pagenation/index.vue";
import {
  getSearchTimes,
  getShortCuts,
  removeEmptyLines,
  tableTimeDateMsg,
} from "@/utils/utils";

//* 变量声明
const loading = ref(false);
const demandsList = ref<any>([]); //所有需求数据列表
const projecOptions = ref<any>([]); //所有项目下拉列表
const wikiOptions = ref<any>([]); //所有项目下拉列表
const testOptions = ref<any>([]); //所有的测试人员下拉列表

//* 弹窗部分
const isCreateDialog = ref(false); //是否创建需求
const titleDialogText = ref(""); //添加或修改标题文本

const dialogWikiIsArchivingVisible = ref(false); //是否归档弹框
const dialogTableVisible = ref(false); //添加/修改需求弹窗控件
const dialogViewVisible = ref(false); //查看需求弹窗控件
const dialogTestVisible = ref(false); //查看、上传、审核用例弹窗控件
const caseVisible = ref(false); //修改用例弹窗控件
const auditVisible = ref(false); //审核用例弹窗控件

const uploadCaseFile = ref<File>(); //待上传文件
const uploadTipText = ref(""); //提示文字
const reqData = reactive({
  id: null,
  page: 1,
  pageSize: 999,
}); //获取当前需求所有用例的请求参数初始值
const reqCaseData = reactive({
  requirementId: null,
  itemItemId: null,
  filePath: "",
}); //导入用例请求参数

const initCaseData = ref<any>([]); //用例表格初始值

const dialogFormRef = ref(); //添加/修改需求表单实例
const requireID = ref(); //需求id

// 初始化表单数据
const initDialogFormData = () => ({
  itemItemId: 1,
  itemWIKITypeId: 1,
  beginDate: null,
  endDate: null,
  auxiliaryUser: "",
  developmentBBTime: "",
  isTrue: 1,
  isArchiving: 0,
  archivingUrl: "",
  problemReason: "",
  trueResult: "",
  problemMsg: "",
  problemPhoto: "",
});
const dialogFormData: any = reactive(initDialogFormData());

// 自定义表单规则
const validatorTmName = (rule: any, value: any, callBack: any) => {
  console.log(rule);
  console.log(value.includes("img src"));
  // 校验通过
  if (value.includes("img src")) {
    callBack();
  } else {
    // 检验未通过
    callBack(new Error("必须包含截图"));
  }
};
// 弹窗表单校验规则
const ruleDialogForm = reactive({
  projectid: [
    {
      itemItemId: true,
      message: "请选择项目名称",
      trigger: "blur",
    },
  ],
  itemWIKITypeId: [
    {
      required: true,
      message: "请选择wiki类型",
      trigger: "blur",
    },
  ],
  problemMsg: [
    {
      required: true,
      message: "请输入问题描述",
      trigger: "blur",
    },
  ],
  problemReason: [
    {
      required: true,
      message: "请输入问题原因",
      trigger: "blur",
    },
  ],
  trueResult: [
    {
      required: true,
      message: "请输入处理情况",
      trigger: "blur",
    },
  ],
  beginDate: [
    {
      required: true,
      message: "请选择开始时间",
      trigger: "blur",
    },
  ],
  endDate: [
    {
      required: true,
      message: "请选择结束时间",
      trigger: "blur",
    },
  ],
  isTrue: [
    {
      required: true,
      message: "请选择是否解决",
      trigger: "blur",
    },
  ],
  problemPhoto: [
    {
      required: true,
      validator: validatorTmName,
      trigger: "blur",
    },
  ],
});

const pageInfo = reactive({
  total: 0, //总条目
  page: 1, //当前页码
  pageSize: 20, //当前每页条数
});
//关键词数据默认值
const searchFormData = reactive({
  itemItemId: null,
  sysUserId: null,
  itemWIKITypeId: null,
  isTrue: null,
  problemMsg: "",
  timeFrame: getSearchTimes(new Date()),
});

const tableHeaderStyle = {
  backgroundColor: "#F2F6FC",
  color: "#909399",
  textAlign: "center",
};
const tableRowStyle = {
  cursor: "pointer",
  backgroundColor: "#fff",
};

const requirementContetnStyle: { [key: string]: string } = {
  whiteSpace: "wrap",
  lineHeight: "200%",
  cursor: "pointer",
};

// 查看wiki初始值
const dialogViewData: any = reactive({
  id: 0,
  createUser: "",
  projectName: 0,
  processingDate: "",
  beginDate: "0001-01-01T00:00:00Z",
  endDate: "0001-01-01T00:00:00Z",
  auxiliaryUser: "",
  developmentBBTime: "",
  isTrue: 0,
  isArchiving: 0,
  archivingUrl: "",
  problemReason: "",
  trueResult: "",
  problemMsg: "",
  problemPhoto: "",
  itemWIKITypeName: "",
});

//? 修改用例
// 表单实例
const caseDlgFormRef = ref();
// 表单初始化方法
const initCaseDlgFormData = () => ({
  id: null,
  caseName: "",
  operationSteps: "",
  expectedResult: "",
  realResult: "",
});
// 图片放大功能
const dialogVisible = ref(false);
const currentImageSrc = ref("");
const content = ref<HTMLElement | null>(null);
//表单初始值
const caseDlgFormData = reactive(initCaseDlgFormData());

//? 是否归档
const archivingFormRef = ref();
const initArchivingFormData = () => ({
  id: null,
  archivingUrl: <any>"",
  isArchiving: 0,
});
const archivingFormData = reactive(initArchivingFormData());

//* 功能函数
// 时间快捷选择器
const shortcuts = getShortCuts();

// @ts-ignore 时间格式化
const timeDate = (row: any, column: any, cellValue: any, index: number) => {
  return tableTimeDateMsg(cellValue);
};

// 获取所有wiki数据列表-demandsList
const getDemandsList = async () => {
  loading.value = true;

  const resData = await getWikiList({
    itemItemId:
      searchFormData.itemItemId != "" ? searchFormData.itemItemId : null,
    sysUserId: searchFormData.sysUserId != "" ? searchFormData.sysUserId : null,
    isTrue: searchFormData.isTrue != "" ? searchFormData.isTrue : null,
    itemWIKITypeId:
      searchFormData.itemWIKITypeId != ""
        ? searchFormData.itemWIKITypeId
        : null,
    problemMsg: searchFormData.problemMsg,
    beginDate:
      searchFormData.timeFrame !== null
        ? searchFormData.timeFrame[0]
        : "0001-01-01T00:00:00Z",
    endDate:
      searchFormData.timeFrame !== null
        ? new Date(new Date(searchFormData.timeFrame[1]).setHours(23, 59, 59))
        : new Date(),
    page: pageInfo.page,
    pageSize: pageInfo.pageSize,
  });

  if (resData.data.code === 200 && resData.data.data.list !== null) {
    pageInfo.total = resData.data.data.total;
    pageInfo.page = resData.data.data.page;
    pageInfo.pageSize = resData.data.data.pageSize;
    demandsList.value = resData.data.data.list; //所有需求数据列表
  } else {
    ElMessage.error(resData.data.msg);
    loading.value = false;
    return;
  }
  loading.value = false;
};
// 更改每页条目数
const handleSizeChange = async (val: any) => {
  pageInfo.pageSize = val;
  pageInfo.page = 1;
  await getDemandsList();
};
// 更改当前页码
const handleCurrentChange = async (val: any) => {
  pageInfo.page = val;
  await getDemandsList();
};

// 获取所有项目下拉列表-projecOptions
const getProjectOptons = async () => {
  loading.value = true;
  const resData = await getItemList({});
  if (resData.data.code === 200 && resData.data.data.length != 0) {
    // 所有项目下拉列表
    projecOptions.value = resData.data.data.map((item: any) => {
      return { ID: item.ID, itemName: item.itemName };
    });
  } else {
    ElMessage.error("未获取到项目数据列表");
    loading.value = false;
    return;
  }
  loading.value = false;
};

// 获取所有wiki类型下拉列表-getWikiTypeOptons
const getWikiTypeOptons = async () => {
  loading.value = true;
  const resData = await getWikiTypeList();
  if (resData.data.code === 200 && resData.data.data.length != 0) {
    // 所有项目下拉列表
    wikiOptions.value = resData.data.data.map((wiki: any) => {
      return { ID: wiki.ID, typeName: wiki.typeName };
    });
  } else {
    ElMessage.error("未获取到项目数据列表");
    loading.value = false;
    return;
  }
  loading.value = false;
};

// 获取所有测试人员列表-testOptions
const getAllTestOptions = async () => {
  loading.value = true;
  const resData = await getTestList();
  if (resData.data.code === 200 && resData.data.data.length != 0) {
    // 所有测试人员下拉列表
    testOptions.value = resData.data.data.map((item: any) => {
      return { id: item.id, testName: item.nickName };
    });
  } else {
    ElMessage.error("未获取到测试人员列表");
    loading.value = false;
    return;
  }
  loading.value = false;
};

// 搜索功能
const handleSearch = async () => {
  loading.value = true;
  await getDemandsList();
  loading.value = false;
};

//! 导出功能
const downloadFromEndpoint = async (endpoint: any, Data: any) => {
  try {
    const response = await request({
      url: endpoint,
      method: "POST",
      responseType: "blob", // 重要：设置响应类型为 blob
      data: Data, // 添加请求参数
      headers: {
        "Content-Type": "application/json", // 根据实际情况设置请求头
      },
    });
    const blob = new Blob([response.data], {
      type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
    });
    const url = window.URL.createObjectURL(blob);
    const link = document.createElement("a");
    link.href = url;
    link.setAttribute("download", "export.xlsx");
    link.style.visibility = "hidden";
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
  } catch (error) {
    console.error("下载文件出错:", error);
  }
};

const handleExport = async () => {
  loading.value = true;

  const postData = {
    itemItemId:
      searchFormData.itemItemId != "" ? searchFormData.itemItemId : null,
    sysUserId: searchFormData.sysUserId != "" ? searchFormData.sysUserId : null,
    isTrue: searchFormData.isTrue != "" ? searchFormData.isTrue : null,
    itemWIKITypeId:
      searchFormData.itemWIKITypeId != ""
        ? searchFormData.itemWIKITypeId
        : null,
    problemMsg: searchFormData.problemMsg,
    beginDate:
      searchFormData.timeFrame !== null
        ? searchFormData.timeFrame[0]
        : "0001-01-01T00:00:00Z",
    endDate:
      searchFormData.timeFrame !== null
        ? new Date(new Date(searchFormData.timeFrame[1]).setHours(23, 59, 59))
        : new Date(),
  };

  downloadFromEndpoint("/wiki/exportThisMonthWikis", postData);

  loading.value = false;
};

// 选择文件后临时保存
const handleBeforeUpload = async (file: any) => {
  uploadCaseFile.value = file;
  if (uploadCaseFile.value == undefined) {
    uploadTipText.value = "请先选择用例";
  } else {
    // 选择并上传用例
    const resData = await postUploadCaseFile(uploadCaseFile.value);
    // 上传成功则直接导入用例
    if (resData.data.code === 200) {
      ElMessage.success(resData.data.msg);
      reqCaseData.filePath = resData.data.data.filePath;

      // 导入用例
      const resCaseData = await postRequirementCase(reqCaseData);
      // 导入用例成功则刷新用例表格
      if (resCaseData.data.code === 200) {
        ElMessage.success(resCaseData.data.msg);
        await getDemandsList();

        // 重新获取用例
        const resDataList = await getRequirementCase(reqData);
        if (
          resDataList.data.code === 200 &&
          resDataList.data.data.list !== null
        ) {
          initCaseData.value = resDataList.data.data.list;
        } else {
          // 获取用例失败提示
          ElMessage.error(resDataList.data.msg);
          throw Error(resDataList.data.msg);
        }
      } else {
        // 导入失败提示
        ElMessage.error(resCaseData.data.msg);
        throw Error(resCaseData.data.msg);
      }
    } else {
      // 上传失败提示
      ElMessage.error(resData.data.msg);
      throw new Error(resData.data.msg);
    }
  }
  return false;
};

// 关闭/取消用例弹窗事件
const closeCasesDialog = () => {
  dialogTestVisible.value = false; //关闭弹窗
  reqData.id = null;
  reqCaseData.filePath = "";
  reqCaseData.itemItemId = null;
  reqCaseData.requirementId = null;
};
// 关闭/取消修改用例弹窗事件
const closeCaseDialog = () => {
  caseVisible.value = false; //关闭弹窗
  initCaseDlgFormData(); //初始化表单数据
};

// 关闭/取消审核用例弹窗事件
const closeWikiArchivingDialog = () => {
  dialogWikiIsArchivingVisible.value = false;
  initArchivingFormData();
};

// 定义不同用例质量的颜色
const getQualityColor = (quality: number) => {
  switch (quality) {
    case 3:
      return "green"; // 优 - 绿色
    case 2:
      return "blue"; // 良 - 蓝色
    default:
      return "red"; // 差 - 红色
  }
};

// 确认删除用例
const handleDelTest = async (id: number) => {
  const resData = await delCaseByid(id);
  if (resData.data.code === 200) {
    ElMessage.success(resData.data.msg);
    // 重新获取用例
    const resDataList = await getRequirementCase(reqData);
    if (resDataList.data.code === 200 && resDataList.data.data.list !== null) {
      initCaseData.value = resDataList.data.data.list;
    } else {
      // 获取用例失败提示
      ElMessage.error(resDataList.data.msg);
      throw Error(resDataList.data.msg);
    }
  } else {
    ElMessage.error(resData.data.msg);
    throw new Error(resData.data.msg);
  }
};
// 提交归档数据数据
const submitWikiArchivingFormData = async () => {
  const resData = await putWikiArchiving(archivingFormData);
  if (resData.data.code == 200) {
    ElMessage.success(resData.data.msg);
    dialogWikiIsArchivingVisible.value = false;
  } else {
    ElMessage.error(resData.data.msg);
    throw new Error(resData.data.msg);
  }
  await getDemandsList();
  auditVisible.value = false;
};

// 审核功能
const handleAuditTest = (row: any) => {
  console.log("审核：", row);
};

// 开启修改用例弹窗
const handleEditTest = (row: any) => {
  caseVisible.value = true;
  initCaseDlgFormData(); //表单初始化
  caseDlgFormData.id = row.ID;
  caseDlgFormData.caseName = row.caseName;
  caseDlgFormData.operationSteps = row.operationSteps;
  caseDlgFormData.expectedResult = row.expectedResult;
  caseDlgFormData.realResult = row.realResult;
};

// 提交修改后的用例
const submitCaseFormData = async () => {
  const resData = await putEditeCaseByid(caseDlgFormData);
  if (resData.data.code == 200) {
    ElMessage.success(resData.data.msg);
    // 重新获取用例
    const resDataList = await getRequirementCase(reqData);
    if (resDataList.data.code === 200 && resDataList.data.data.list !== null) {
      initCaseData.value = resDataList.data.data.list;
    } else {
      // 获取用例失败提示
      ElMessage.error(resDataList.data.msg);
      throw Error(resDataList.data.msg);
    }
  } else {
    ElMessage.error(resData.data.msg);
    throw new Error(resData.data.msg);
  }
  caseVisible.value = false;
};

//* 添加/修改弹窗表单校验
const validateForm = (form: any) => {
  return new Promise<boolean>((resolve, reject) => {
    form.validate((valid: boolean) => {
      if (valid) {
        resolve(true);
      } else {
        reject(new Error("请按要求填写需求！"));
      }
    });
  });
};

// 开启是否归档弹框
const isArchivingForm = async (row: any) => {
  console.log(row);
  // 是否归档弹出框
  dialogWikiIsArchivingVisible.value = true;
  initArchivingFormData(); //表单初始化
  if (row !== null) {
    archivingFormData.id = row.ID;
    archivingFormData.archivingUrl = row.archivingUrl;
    archivingFormData.isArchiving = row.isArchiving;
  }
};

// 开启添加/修改wiki弹窗
const initDialogForm = async (row: any) => {
  dialogTableVisible.value = true;
  initDialogFormData(); //表单初始化
  if (row !== null) {
    //* 修改wiki
    isCreateDialog.value = false;
    titleDialogText.value = "修改";
    // 其它非测试人员默认为其它
    if (row.ItemItemId == 0) {
      dialogFormData.projectid = 32;
    } else {
      dialogFormData.projectid = row.ItemItemId; //项目ID
    }
    requireID.value = row.ID; //wiki ID
    const resData = await getWikiMsg(row.ID); //根据wiki id获取详细信息
    const data = resData.data.data;
    if (resData.data.code === 7) {
      ElMessage.error(resData.data.msg);
      throw new Error();
    } else {
      dialogFormData.createUser = data.createUser;
      dialogFormData.itemWIKITypeId = data.itemWIKITypeId;
      dialogFormData.itemItemId = data.itemItemId;
      dialogFormData.projectName = data.projectName;
      dialogFormData.beginDate =
        data.beginDate == "0001-01-01T00:00:00Z"
          ? null
          : tableTimeDateMsg(data.beginDate);
      dialogFormData.endDate =
        data.endDate == "0001-01-01T00:00:00Z"
          ? null
          : tableTimeDateMsg(data.endDate);
      dialogFormData.auxiliaryUser = data.auxiliaryUser;
      dialogFormData.developmentBBTime = data.developmentBBTime;
      dialogFormData.isTrue = data.isTrue;
      dialogFormData.isArchiving = data.isArchiving;
      dialogFormData.archivingUrl = data.archivingUrl;
      dialogFormData.problemReason = data.problemReason;
      dialogFormData.trueResult = data.trueResult;
      dialogFormData.problemMsg = data.problemMsg;
      // 去除空行
      dialogFormData.problemPhoto = removeEmptyLines(data.problemPhoto);
    }
  } else {
    //* 添加需求
    isCreateDialog.value = true;
    titleDialogText.value = "添加";
  }
};

// 富文本数据更新
const updateModelValue = (newContent: any) => {
  dialogFormData.problemPhoto = newContent;
  return dialogFormData.problemPhoto;
};

//添加wiki
const handleTrue = async () => {
  const resData = await postAddWIki(dialogFormData).finally(() => {
    // 无论表单提交是否成功，都执行
    dialogTableVisible.value = false;
    loading.value = false;
    Object.assign(dialogFormData, initDialogFormData());
  });
  if (resData.data.code == 200) {
    ElMessage.success(`${titleDialogText.value}WIKI成功！`);
    await getDemandsList(); //重新获取所有wiki数据
  } else {
    ElMessage.error(resData.data.msg);
    throw new Error();
  }
};

//* 确定添加/修改需求功能
const handleAddRequire = async () => {
  loading.value = true;
  // 确定时监听富文本内容
  const addBtn = document.querySelector("#addBtn");
  addBtn?.addEventListener("update:modelValue", updateModelValue);

  // 提交需求到服务器
  if (isCreateDialog.value) {
    // * 添加需求
    dialogFormData.id = undefined;
    await validateForm(dialogFormRef.value);

    handleTrue();
  } else {
    // * 修改需求
    dialogFormData.id = requireID.value;
    // 需要转下时间格式
    // 创建一个Date对象
    const begindateObj = new Date(dialogFormData.beginDate);
    const endDateObj = new Date(dialogFormData.endDate);
    // 转换为指定格式
    dialogFormData.beginDate = begindateObj.toISOString();
    dialogFormData.endDate = endDateObj.toISOString();
    // @ts-ignore
    const resData = await editWikiMsg(dialogFormData).finally(() => {
      // 无论表单提交是否成功，都执行
      dialogTableVisible.value = false;
      loading.value = false;
      Object.assign(dialogFormData, initDialogFormData());
    });
    if (resData.data.code == 200) {
      ElMessage.success(resData.data.msg);
      await getDemandsList(); //重新获取所有wiki数据
    } else {
      ElMessage.error(resData.data.msg);
      throw new Error();
    }
  }
};

// 取消/关闭添加/修改需求
const handleCancel = () => {
  dialogTableVisible.value = false;
  loading.value = false;
  Object.assign(dialogFormData, initDialogFormData());
};
const handleBeforeCancel = (done: any) => {
  dialogTableVisible.value = false;
  loading.value = false;
  Object.assign(dialogFormData, initDialogFormData());
  done();
};

//* 查看wiki详细信息
const handleViewRequire = async (wikiMsg: any) => {
  let wiki;
  if (typeof wikiMsg != "number") {
    wiki = wikiMsg.ID;
  } else {
    wiki = wikiMsg;
  }
  dialogViewVisible.value = true;
  const resData = await getWikiMsg(wiki);
  const data = resData.data.data;
  if (resData.data.code === 7) {
    ElMessage.error(resData.data.msg);
    throw new Error();
  } else {
    const resWikiTypeData = await getWikiTypeById(data.itemWIKITypeId);
    if (resData.data.code === 7) {
      ElMessage.error(resData.data.msg);
      throw new Error();
    } else {
      dialogViewData.itemWIKITypeName = resWikiTypeData.data.data.typeName;
    }
    dialogViewData.createUser = data.createUser;
    dialogViewData.projectName = data.projectName;
    dialogViewData.processingDate = data.processingDate;
    dialogViewData.beginDate =
      data.beginDate == "0001-01-01T00:00:00Z"
        ? null
        : tableTimeDateMsg(data.beginDate);
    dialogViewData.endDate =
      data.endDate == "0001-01-01T00:00:00Z"
        ? null
        : tableTimeDateMsg(data.endDate);
    dialogViewData.auxiliaryUser = data.auxiliaryUser;
    dialogViewData.developmentBBTime = data.developmentBBTime;
    dialogViewData.isTrue = data.isTrue;
    dialogViewData.isArchiving = data.isArchiving;
    dialogViewData.archivingUrl = data.archivingUrl;
    dialogViewData.problemReason = data.problemReason;
    dialogViewData.trueResult = data.trueResult;
    dialogViewData.problemMsg = data.problemMsg;
    // 去除空行
    dialogViewData.problemPhoto = removeEmptyLines(data.problemPhoto);
    // 打开详情的时候注册事件查看图片大图
    nextTick(() => {
      addImageClickHandler();
    });
  }
};

// 为图片添加点击事件监听器
const addImageClickHandler = () => {
  if (content.value) {
    const images = content.value.querySelectorAll("img");
    images.forEach((img) => {
      img.addEventListener("click", () => {
        currentImageSrc.value = img.src;
        dialogVisible.value = true;
      });
    });
  }
};

// 确认删除需求
const handleDelRequire = async (id: number) => {
  const resData = await delWiki(id);
  if (resData.data.code === 200) {
    ElMessage.success(resData.data.msg);
    await getDemandsList();
  } else {
    ElMessage.error(resData.data.msg);
    throw new Error();
  }
};
// 取消删除需求
const handleCancelDel = () => {
  ElMessage.info("取消删除！");
  return;
};

onMounted(() => {
  getProjectOptons();
  getWikiTypeOptons();
  getDemandsList();
  getAllTestOptions();
  window.addEventListener("update:modelValue", updateModelValue);
});
</script>

<style scoped lang="scss">
// 文本溢出省略
.cell-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

// 快捷筛选
.card-wrap-count-search {
  display: inline-block;
  padding: 5px;
  margin-right: 10px;
  background-color: #f2f3f5;
  border-radius: 2px;
  cursor: pointer;
}

.card-wrap-count-search:hover {
  background-color: #a0cfff;
}

// 操作按钮
.table-operation {
  width: 36px;
  height: 26px;
  padding: 0 10px;
  display: inline-block;
  color: #409eff;
}

.table-operation-view:hover,
.table-operation-edit:hover {
  background-color: #409eff;
  color: white;
}

.table-operation-del:hover {
  background-color: #ff343f;
  color: white;
}

/* 添加需求弹窗 */
.el-dialog {
  --el-dialog-margin-top: 20px;

  .dialog-form {
    .el-form-item {
      padding-left: 5px;
    }
  }
}

/* 查看需求 */
.dialog-view-requireTitle {
  font-weight: bold;
}

.el-row {
  border-left: 1px solid #eee;
  border-right: 1px solid #eee;
  text-align: left;
}

.el-col {
  border: 1px solid #eee;
  padding: 10px 0;
}

/* 用例总览区域 */
.case-item {
  display: flex;
  justify-content: space-between;
  margin-top: 5px;
  color: #303133;

  p {
    background-color: #f2f3f5;
    border-radius: 2px;
    padding: 5px 10px;
  }
}

// 隐藏过长显示
.table-cell {
  white-space: nowrap;
  /* 不换行 */
  overflow: hidden;
  /* 溢出部分隐藏 */
  text-overflow: ellipsis;
  /* 以省略号表示溢出部分 */
}

/* 审核用例详情 */
.case-info-wrap {
  width: 100%;
  display: flex;
  flex-direction: column;

  .case-info-item {
    display: flex;
    justify-content: left;

    .case-info-title {
      width: 90px;
      margin-bottom: 20px;
      line-height: 150%;
    }

    .case-info-text {
      line-height: 150%;
      margin-bottom: 20px;
    }
  }
}
</style>

<style lang="scss">
.is-dark {
  width: 200px;
  opacity: 0.8;
}

.el-table {
  --el-table-row-hover-bg-color: #d9ecff;
}

.el-dialog {
  --el-dialog-margin-top: 50px;
}

.el-dialog__body {
  padding: 10px 20px 30px;
}
</style>
